package com.ruoyi.web.controller.system;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.web.controller.domain.ConsumeUnionDataResponse;
import com.ruoyi.web.controller.domain.FranchiserDataResponse;
import com.ruoyi.web.controller.domain.SendItemResponse;
import com.ruoyi.web.controller.domain.SmsResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.*;

/**
 * 平台服务
 */
@Service
public class PlatformService extends BaseController {
    public static final int LANGUAGE_1 = 1;  // 葡语
    @Value("${platform.host}")
    String HOST;
    @Value("${platform.appSecret}")
    String APP_SECRET;

    /**
     * 推广员列表数据
     *
     * @param franchiserId 分销商ID
     * @param page         页码
     * @return 推广员列表数据
     */
    public List<FranchiserDataResponse.FranchiserData> franchiserList(int franchiserId, int page) {
        // page 从1开始？
        // 每页50个数据
        String strUrl = HOST + "/playjoy/api/franchiserList";
        Map<String, String> headers = getJsonHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("page", page);
        body.put("franchiserId", franchiserId);
        body.put("time", System.currentTimeMillis() / 1000L);
        body.put("sign", calcSign(body));
        try {
            String strResponse = HttpUtils.sendPost(strUrl, JsonUtil.serialize(body), headers);
            logger.info(String.format("url: %s, headers: %s, body: %s, response: %s", strUrl,
                    JsonUtil.serialize(headers), JsonUtil.serialize(body), strResponse == null ? "null" : strResponse));
            FranchiserDataResponse response = JsonUtil.deserialize(strResponse, FranchiserDataResponse.class);
            if (response.getCode() == 0) {
                return response.getData().getInfos();
            }
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    private Map<String, String> getJsonHeaders() {
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json");
        return headers;
    }


    public List<ConsumeUnionDataResponse.ConsumeUnionData> consumeUnionDataList(int franchiserId, int queryId) {
        String strUrl = HOST + "/playjoy/api/consumeUnionData";
        Map<String, String> headers = getJsonHeaders();
        Map<String, Object> body = new HashMap<>();
//        body.put("beginTime", beginTime);
//        body.put("endTime", endTime);
        body.put("franchiserId", franchiserId);
        body.put("queryId", queryId);
        body.put("beginTime", System.currentTimeMillis() / 1000L - 10 * 86400l);
        body.put("endTime", System.currentTimeMillis() / 1000L);
        body.put("time", System.currentTimeMillis() / 1000L);
        body.put("sign", calcSign(body));
        try {
            String strResponse = HttpUtils.sendPost(strUrl, JsonUtil.serialize(body), headers);
            logger.info(String.format("url: %s, headers: %s, body: %s, response: %s", strUrl,
                    JsonUtil.serialize(headers), JsonUtil.serialize(body), strResponse == null ? "null" : strResponse));
            ConsumeUnionDataResponse response = JsonUtil.deserialize(strResponse, ConsumeUnionDataResponse.class);
            if (response.getCode() == 0) {
                return response.getData();
            }
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 发放道具
     *
     * @param account 发放者
     * @param target  接受ID
     * @param change  发放的数量 可以小数
     * @return
     */
    public SendItemResponse sendItem(int account, int target, double change) {
        String strUrl = HOST + "/playjoy/api/sendItem";
        Map<String, String> headers = getJsonHeaders();
        Map<String, Object> body = new HashMap<>();
        body.put("account", account);
        body.put("target", target);
        body.put("change", change);
        body.put("time", System.currentTimeMillis() / 1000L);
        body.put("sign", calcSign(body));
        try {
            String strResponse = HttpUtils.sendPost(strUrl, JsonUtil.serialize(body), headers);
            logger.info(String.format("url: %s, headers: %s, body: %s, response: %s", strUrl,
                    JsonUtil.serialize(headers), JsonUtil.serialize(body), strResponse == null ? "null" : strResponse));
            SendItemResponse response = JsonUtil.deserialize(strResponse, SendItemResponse.class);
            if (response.getCode() == 0) {
                return response;
            }
            //<br> 错误码：<br> 0:正常<br> -1: 发放人和接收人同一个<br> -2:发放数值<= 0<br> -3：发放人被封号<br> -4:找不到接收人的账号<br> -5:发放人钱不够<br> -100:发放人和被发放人之间至少有一个因为服务器硬件异常，拿不到玩家所在的服务器<br>
            logger.error(String.format("sendItem error, url: %s, headers: %s, body: %s, response: %s", strUrl,
                    JsonUtil.serialize(headers), JsonUtil.serialize(body), strResponse == null ? "null" : strResponse));
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    public String calcSign(Map<String, Object> params) {
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        String str = "";
        for (String key : keys) {
            if (str.length() == 0) {
                str = key + "=" + params.get(key);
            } else {
                str += "&" + key + "=" + params.get(key);
            }
        }
        str += "&" + APP_SECRET;
        return Md5Utils.hash(str);
    }

    public boolean sendCodeMsg(String strPhoneNumber, String validCode, int expiredMinute, int language) {
        // http://1.15.129.166:8351/http-document?spid=309650&pwd=1fabcd32673e408696c605fb92ca5b3f
        try {
            String strUrl = "http://1.15.129.166:9511/api/send-sms-single";

            String context = language == LANGUAGE_1 ? "%s, este é seu código de verificação. Não o encaminhe para outros. Válido por %d minutos." : "%s es su código de verificación. Por favor, no lo comparta con nadie más. Válido durante %d minutos.";
            context = String.format(context, validCode, expiredMinute);
            context = URLEncoder.encode(context, "UTF-8");
            String body = String.format("sp_id=309650&mobile=%s&content=%s&password=1fabcd32673e408696c605fb92ca5b3f", strPhoneNumber, context);
            Map<String, String> headers = new HashMap<>();
            headers.put("content-type", "application/x-www-form-urlencoded");
            String response = HttpUtils.sendPost(strUrl, body, headers);
            logger.info(String.format("url: %s, headers: %s, body: %s, response: %s", strUrl,
                    JsonUtil.serialize(headers), JsonUtil.serialize(body), response == null ? "null" : response));
            SmsResponse res = JsonUtil.deserialize(response, SmsResponse.class);
            if (res.getCode() != 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return false;
        }
    }
}
